<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="项目名称" prop="proName">
        <el-input v-model="queryParams.proName" placeholder="请输入项目名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="权限等级" prop="permissionLevel">
        <el-select v-model="queryParams.permissionLevel" placeholder="请选择权限等级" clearable style="width: 200px">
          <el-option label="普通用户" value="0" />
          <el-option label="管理员" value="1" />
          <el-option label="超级管理员" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['userProject:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleEdit"
          v-hasPermi="['userProject:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['userProject:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['userProject:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userProjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" prop="id" width="80" align="center" />
      <el-table-column label="用户名称" prop="userName" min-width="120" align="center" />
      <el-table-column label="项目名称" prop="proName" min-width="120" align="center" />
      <el-table-column label="权限等级" prop="permissionLevel" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.permissionLevel === 0" style="color: #1890ff;">普通用户</span>
          <span v-else-if="scope.row.permissionLevel === 1" style="color: #52c41a;">管理员</span>
          <span v-else-if="scope.row.permissionLevel === 2" style="color: #ff4d4f;">超级管理员</span>
        </template>
      </el-table-column>
      <el-table-column label="最大生成激活码数量" prop="maxActivationCount" width="140" align="center">
        <template #default="scope">
          {{ scope.row.maxActivationCount === 0 ? '无限制' : scope.row.maxActivationCount }}
        </template>
      </el-table-column>
      <el-table-column label="总积分" prop="totalPoints" width="100" align="center" />
      <el-table-column label="可用积分" prop="availablePoints" width="100" align="center" />
      <el-table-column label="状态" prop="status" width="80" align="center">
        <template #default="scope">
          <span v-if="scope.row.status === 1" style="color: #52c41a;">启用</span>
          <span v-else style="color: #ff4d4f;">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="createBy" width="100" align="center" />
      <el-table-column label="创建时间" prop="createTime" width="180" align="center" />
      <el-table-column label="更新者" prop="updateBy" width="100" align="center" />
      <el-table-column label="更新时间" prop="updateTime" width="180" align="center" />
      <el-table-column label="备注" prop="remark" min-width="120" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)" v-hasPermi="['userProject:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['userProject:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户项目对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="userProjectForm" :model="userProject" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户" prop="userId">
              <el-select v-model="userProject.userId" placeholder="请选择用户" filterable clearable @change="handleUserChange">
                <el-option
                  v-for="user in userOptions"
                  :key="user.userId"
                  :label="user.userName"
                  :value="user.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目" prop="proId">
              <el-select v-model="userProject.proId" placeholder="请选择项目" filterable clearable @change="handleProjectChange">
                <el-option
                  v-for="project in projectOptions"
                  :key="project.id"
                  :label="project.proName"
                  :value="project.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限等级" prop="permissionLevel">
              <el-select v-model="userProject.permissionLevel" placeholder="请选择权限等级">
                <el-option label="普通用户" :value="0" />
                <el-option label="管理员" :value="1" />
                <el-option label="超级管理员" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大生成激活码数量" prop="maxActivationCount">
              <el-input v-model="userProject.maxActivationCount" placeholder="请输入最大生成激活码数量（0表示无限制）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总积分" prop="totalPoints">
              <el-input v-model="userProject.totalPoints" placeholder="请输入总积分" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可用积分" prop="availablePoints">
              <el-input v-model="userProject.availablePoints" placeholder="请输入可用积分" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch v-model="userProject.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="userProject.remark" type="textarea" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUserProject, getUserProject, addUserProject, updateUserProject, delUserProject, exportUserProject } from '@/api/userProject'
import { listUser } from '@/api/system/user'
import { listProject } from '@/api/project'

export default {
  name: 'UserProject',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户项目关联列表
      userProjectList: [],
      // 用户选项
      userOptions: [],
      // 项目选项
      projectOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        proName: '',
        permissionLevel: null,
        status: null
      },
      // 表单参数
      userProject: {
        id: null,
        userId: null,
        userName: '',
        proId: null,
        proName: '',
        permissionLevel: 0,
        maxActivationCount: 0,
        totalPoints: 0,
        availablePoints: 0,
        status: 1,
        remark: ''
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: '用户不能为空', trigger: 'change' }
        ],
        proId: [
          { required: true, message: '项目不能为空', trigger: 'change' }
        ],
        permissionLevel: [
          { required: true, message: '权限等级不能为空', trigger: 'change' }
        ],
        maxActivationCount: [
          { required: true, message: '最大生成激活码数量不能为空', trigger: 'blur' },
          { type: 'number', message: '请输入有效数字', trigger: 'blur' }
        ],
        totalPoints: [
          { type: 'number', message: '请输入有效数字', trigger: 'blur' }
        ],
        availablePoints: [
          { type: 'number', message: '请输入有效数字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getUsers()
    this.getProjects()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      listUserProject(this.queryParams).then(res => {
        this.userProjectList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    /** 查询用户列表 */
    getUsers() {
      listUser().then(res => {
        this.userOptions = res.rows
      })
    },
    /** 查询项目列表 */
    getProjects() {
      listProject({ status: 1 }).then(res => {
        this.projectOptions = res.rows
      })
    },

    /** 搜索按钮点击事件 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮点击事件 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮点击事件 */
    handleAdd() {
      this.reset()
      this.title = '新增用户项目关联'
      // 先设置表单状态，再显示弹窗，确保正确的DOM更新时序
      this.$nextTick(() => {
        this.open = true
      })
    },
    /** 修改按钮点击事件 */
    handleEdit(row) {
      this.reset()
      const id = row.id || this.ids
      getUserProject(id).then(res => {
        // 修复：正确地从响应中提取数据
        this.userProject = res.data
        this.open = true
        this.title = '修改用户项目关联'
      })
    },
    /** 用户选择变化事件 */
    handleUserChange(value) {
      if (value) {
        const user = this.userOptions.find(item => item.userId === value)
        if (user) {
          this.userProject.userName = user.userName
        }
      } else {
        this.userProject.userName = ''
      }
    },
    /** 项目选择变化事件 */
    handleProjectChange(value) {
      if (value) {
        const project = this.projectOptions.find(item => item.id === value)
        if (project) {
          this.userProject.proName = project.proName
        }
      } else {
        this.userProject.proName = ''
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['userProjectForm'].validate(valid => {
        if (valid) {
          // 创建一个新对象，不包含userName和proName字段，因为数据库表中不存在这两个字段
          const submitData = {
            ...this.userProject
          }
          // 删除不需要提交的字段
          delete submitData.userName
          delete submitData.proName
          
          if (this.userProject.id != null) {
            updateUserProject(submitData).then(res => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUserProject(submitData).then(res => {
              if (res.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(res.msg)
              }
            })
          }
        }
      })
    },
    /** 重置按钮 */
    reset() {
      this.userProject = {
        id: null,
        userId: null,
        userName: '',
        proId: null,
        proName: '',
        permissionLevel: 0,
        maxActivationCount: 0,
        totalPoints: 0,
        availablePoints: 0,
        status: 1,
        remark: ''
      }
      this.resetForm('userProjectForm')
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 单条删除 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除用户项目关联数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delUserProject(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 批量删除 */
    handleDeleteAll() {
      this.$confirm('是否确认删除选中的用户项目关联数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delUserProject(this.ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮点击事件 */
    handleExport() {
      this.download('userProject/export', { ...this.queryParams }, `userProject_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>

</style>